package com.qsbg.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.qsbg.entity.vo.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;
    private static final String ip = "http://localhost";

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //定义文件的唯一标识(前缀)
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag +"_" + originalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        return ResultVo.ok(ip +":"+ port +"/files/" + flag);
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     * @return
     */
    @GetMapping("/{flag}")
    public ResultVo getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";//定义文件上传根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
        String file = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
        try {
            if(StrUtil.isNotEmpty(file)){
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + file);//通过文件路径读取文件字节流
                os = response.getOutputStream();//通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
                return ResultVo.ok();
            } else{
                return ResultVo.fail("查无此文件");
            }
        }catch (Exception e) {
            System.out.println("文件下载失败");
            return ResultVo.fail("文件下载失败");
        }
    }

    /**
     * 移除图片
     * @param flag
     * @return
     */

    @DeleteMapping("/{flag}")
    public ResultVo delFile(@PathVariable String flag){
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";//定义文件上传根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
        try {
            if(StrUtil.isNotEmpty(fileName)){
                FileUtil.del(basePath + fileName);
                return ResultVo.ok();
            } else{
                return ResultVo.fail("查无此文件");
            }
        }catch (Exception e) {
            System.out.println("文件删除失败");
            return ResultVo.fail("文件删除失败");
        }
    }
}
